import React from 'react'
import {Icon} from 'antd'
import './index.less'

// 使用方法 <Advertise><span>插入行内值</span></Advertise>
export default class Advertise extends React.Component{

  componentDidMount () {
    if (this.refs.ul) {
      window.cancelAnimationFrame(this.myanimation)
      console.log(((window.getComputedStyle(this.refs.left).width.replace('px', '') * 2 + 2) +'px'))
      this.refs.ul.style.width = (window.getComputedStyle(this.refs.left).width.replace('px', '') * 2 + 2) +'px'
      this.myanimation = window.requestAnimationFrame(this.animationAdvertise)
    }

  }
  componentDidUpdate() {
    window.cancelAnimationFrame(this.myanimation)
    console.log((parseInt(window.getComputedStyle(this.refs.left).width.replace('px', '') * 2 + 2) +'px'))
    this.refs.ul.style.width = (window.getComputedStyle(this.refs.left).width.replace('px', '') * 2) +'px'
    this.myanimation = window.requestAnimationFrame(this.animationAdvertise)
  }

  animationAdvertise = (timetap) => {
    if (!this.time) this.time = timetap;
    const progress = timetap - this.time;
    const long = parseInt(window.getComputedStyle(this.refs.left).width.replace('px', '') * 2)
    const width = -Math.max(progress / 20, 0);  // 控制滚动速度

    if (!this.stopWidth) {
      this.stopWidth = 0;
    }
    // console.log( this.stopWidth + width)
    this.refs.ul.style.marginLeft = this.stopWidth + width + 'px'
    if (-(this.stopWidth + width) >= long / 2) {
      console.log(this.stopWidth + width)
      this.refs.ul.style.marginLeft = 0
      this.ulwidth = 0;
      this.time = timetap;
      this.stopWidth = 0;
    } else {
      console.log(this.stopWidth + width)
      this.ulwidth = this.stopWidth + width;
    }

    this.myanimation = window.requestAnimationFrame(this.animationAdvertise)
  }

  onMouseEnter = () => {
    this.time = null;
    window.cancelAnimationFrame(this.myanimation)
  }

  onMouseLeave = () => {
    this.time = null;
    this.stopWidth = this.ulwidth;
    window.cancelAnimationFrame(this.myanimation)
    this.myanimation = window.requestAnimationFrame(this.animationAdvertise)
  }

  render() {
    return <div style={{width: '600px', margin: '50px auto', position: 'relative', paddingLeft: '50px'}}>
      <span className="myspan"><Icon type="sound" /></span>
      <div style={{ overflow: 'hidden', backgroundColor: '#ccc', height: '40px'}}>
        <ul onMouseEnter={this.onMouseEnter}
          onMouseLeave={this.onMouseLeave}
          ref="ul">
          <li ref="left">
            {
              this.props.children
            }
          </li>
          <li>
           {
              this.props.children
            }
          </li>
        </ul>
      </div>

    </div>
  }
}